﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Core;

namespace DietTherapy.Utility
{
 
    public class SnowflakeWorker : IdWorker
    {
        readonly object _lock = new Object();

        private long _lastTimestamp = -1L;

        private long _sequence = 0L;

        public SnowflakeWorker(long workerId, long datacenterId, long sequence = 0) : base(workerId, datacenterId, sequence)
        {
        }

        public override long NextId()
        {
            return base.NextId();
        }

        /// <summary>
        /// 扩展NextId
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public long ReNextId()
        {
            lock (_lock)
            {
                long num = TimeGen();
                if (num < _lastTimestamp)
                {
                    throw new Exception($"时间戳必须大于上一次生成ID的时间戳.  拒绝为{_lastTimestamp - num}毫秒生成id");
                }

                if (_lastTimestamp == num)
                {
                    _sequence = ((_sequence + 1) & 0xFFF);
                    if (_sequence == 0L)
                    {
                        num = TilNextMillis(_lastTimestamp);
                    }
                }
                else
                {
                    _sequence = 0L;
                }

                _lastTimestamp = num;
                return ((num - Twepoch) << 14) | (DatacenterId << 12) | (WorkerId << 6) | _sequence;
            }
        }
    }
 
}
